//
// Created by 33145 on 2023/6/2.
//

#include "tcp_server.h"
#include "../common/rocket.h"
#include "../common/config.h"

namespace rocket {


  TCPServer::TCPServer(NetAddr::ptr local_addr) : _local_addr(local_addr) {
    init();
    LOG_INFO("rocket TcpServer listen success on [%s]", _local_addr->toString().c_str());
  }

  void TCPServer::start() {
    _io_thread_group->start();
    _main_event_loop->loop();
  }

  void TCPServer::init() {
    _acceptor = std::make_shared<TCPAcceptor>(_local_addr);
    _main_event_loop = EventLoop::GetCurrentEventLoop();
    _io_thread_group = std::make_shared<IOThreadGroup>(Config::GetGlobalConfig()->_io_threads);

    _listen_fd_event = std::make_shared<FdEvent>(_acceptor->getListenFd());
    _listen_fd_event->listen(FdEvent::IN_EVENT, [this] { onAccept(); });  // 注册accept回调

    _main_event_loop->addEpollEvent(_listen_fd_event.get());
  }

  void TCPServer::onAccept() {
    auto [client_fd, peer_addr] = _acceptor->accept();
    _listen_client_counts++;

    IOThread::ptr io_thread = _io_thread_group->getIOThread();
    TCPConnection::ptr connection = std::make_shared<TCPConnection>(io_thread->getEventLoop(), client_fd, 128, peer_addr, _local_addr);
    // 在TCPConnection中注册读写的回调事件
    connection->setState(TCPConnection::Connected);
    _clients.insert(connection);
    LOG_INFO("TcpServer success get client, fd=%d", client_fd);
  }
}
